/*
 * Copyright 2006-2007 S W McIlroy
 * Licensed  under the  Apache License,  Version 2.0  (the "License");
 * you may not use  this file  except in  compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed  under the  License is distributed on an "AS IS" BASIS,
 * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
 * implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mockfu;

import static org.mockfu.Mocks.*;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class RuntimeTest
{
    private MockControl<Runtime> runtime;
    private MockControl<Process> process;

    @BeforeMethod
    public void setUp()
    {
        /* we're going to mock the Runtime and Process classes */
        runtime = MockControl.of( Runtime.class );
        process = MockControl.of( Process.class );
        /* inject mock into the static field of type Runtime in class Runtime */
        runtime.injectInto( Runtime.class );
    }

    @AfterMethod
    public void tearDown()
    {
        /* set the Runtime singleton back to its original value */
        runtime.eject();
    }

    @Test
    public void getGateways() throws Exception
    {
        /*
         * define expectation parameter to Runtime.exec(): a String[] with "route" in the first
         * position and the switch -n or -N in the second position
         */
        String[] command = new String[] { "route", matches( "-.*[nN].*" ) };

        /* create a stub value for standard output */
        StringBuilder stdout = new StringBuilder();
        stdout.append( "10.0.1.0  0.0.0.0  255.255.255.0  U  0  0  0 eth1\n" );
        stdout.append( "0.0.0.0  10.0.1.1  0.0.0.0  UG  0  0  0 eth1\n" );
        stdout.append( "random characters\n" );

        /* stub Runtime.exec() to return our Process mock when passed a matching command */
        stub( runtime.expectsOnce().exec( command ), process.mock() );

        /* stub Process.waitFor() to return 0 exit status */
        stub( process.expectsOnce().waitFor(), 0 );
        /* stub Process.getInputStream() to return our standard out string */
        stub( process.expectsOnce().getInputStream(), new ByteArrayInputStream( stdout.toString()
                .getBytes() ) );

        /* create the object we're going to test */
        RouteManager routeManager = new RouteManager();

        /* and execute the method to test */
        List<String> gateways = routeManager.getGateways();

        /* verify expectations were met */
        runtime.verify();
        process.verify();

        /* assert we returned a single gateway of "10.0.1.1" */
        assertThat( gateways, (List<String>)not( null ) );
        assertThat( gateways, equalsSet( "10.0.1.1" ) );
    }
}

class RouteManager
{

    public List<String> getGateways() throws InterruptedException
    {
        try
        {
            List<String> gateways = new ArrayList<String>();

            /* execute system command "route -n" and wait for it to finish */
            Process process = Runtime.getRuntime().exec( new String[] { "route", "-n" } );
            int exitStatus = process.waitFor();
            if( exitStatus != 0 )
                throw new RuntimeException( "route command exited with unexpected status: "
                        + exitStatus );

            /* for each line of standard output, extract the second ip address */
            BufferedReader r = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
            for( String line = null ; (line = r.readLine()) != null ; )
            {
                java.util.regex.Matcher m = Pattern.compile( "[0-9.]+\\s+([0-9.]+)\\s.*" )
                        .matcher( line );
                if( m.matches() )
                {
                    String gateway = m.group( 1 );
                    /* add the gateway unless it's a default route */
                    if( !gateway.equals( "0.0.0.0" ) )
                        gateways.add( gateway );
                }
            }
            return gateways;
        }
        catch( IOException ex )
        {
            throw new RuntimeException( ex );
        }

    }
}